import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import router from '@/router'

// create an axios instance
const service = axios.create({
  baseURL: '/' // url = base url + request url
})

// request interceptor
service.interceptors.request.use(
  (config) => {
    // do something before request is sent

    if (store.getters.token) {
      // please modify it according to the actual situation
      config.headers['authorization'] = getToken()
    }
    return config
  },
  (error) => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  (response) => {
    const res = response.data
    if (res.retcode === 10001) {
      Message.closeAll()
      console.log(router);
      Message({
        message: res.msg || 'Error',
        type: 'error',
        duration: 2 * 1000,
        onClose: async () => {
          await store.dispatch('user/resetToken')
          router.push({ path: '/admin/login'})
        }
      })
      return res
    }
    if (res.retcode !== 200) {
      Message.closeAll()
      Message({
        message: res.msg || 'Error',
        type: 'error',
        duration: 3 * 1000
      })
    }
    return res
  },
  (error) => {
    console.log('err，' + error.response.status) // for debug
    // token过期
    if (error.response.retcode === 401) {
      Message.closeAll()
      Message({
        message: '登录过期，请重新登录',
        type: 'error'
      })
      return Promise.reject(error)
    }
    Message({
      message: error.msg,
      type: 'error',
      duration: 3 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
